package com.example.buyticketlishi.view.ac;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.baselibrary.Base.BaseActivity;
import com.example.baselibrary.Bean.LiShiLoginResultBean;
import com.example.baselibrary.Utils.Customer;
import com.example.baselibrary.Utils.GetDeviceId;
import com.example.baselibrary.Utils.SPUtils;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.ThreadManager;
import com.example.baselibrary.Utils.ToastUtil;
import com.example.buyticketlishi.R;
import com.example.buyticketlishi.RetrufitHelp.BaseSubscriber;
import com.example.buyticketlishi.RetrufitHelp.ExceptionHandle;
import com.example.buyticketlishi.RetrufitHelp.RetrofitClient;
import com.example.buyticketlishi.bean.JJHLoginBean;
import com.example.buyticketlishi.bean.JJHLoginResult;
import com.example.buyticketlishi.server.RefreshTokenService;
import com.example.buyticketlishi.utils.TimeCountDownUtil;
import com.google.gson.Gson;

public class LoginActivity extends BaseActivity {

    private EditText account;
    private EditText password;
    private Button btLogin;
    private Button btQuit;
    private String DeviceId;
    private TextView setIp;

    private JJHLoginBean jjhLoginBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getView() {
        return R.layout.activity_login;
    }

    @Override
    public void init() {

        getDeviceId();
        setIp = (TextView) findViewById(R.id.tv_set_ip);
        setIp.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        account = findViewById(R.id.et_account);
        password = findViewById(R.id.et_password);

        btLogin = findViewById(R.id.bt_login);
        btQuit = findViewById(R.id.bt_quit);

        account.setText((String) SPUtils.get(LoginActivity.this, Customer.LISHI_ACCOUNT, ""));
        password.setText((String) SPUtils.get(LoginActivity.this, Customer.LISHI_PASSWORD, ""));

//        account.setText("administrator");
//        password.setText("888888");

        if ((boolean) SPUtils.get(LoginActivity.this, Customer.LISHI_IS_LOGIN, false)) {
            //如果是已经登录状态那么就
//            ThreadManager.getThreadPool().execute(new Runnable() {
//                @Override
//                public void run() {
//                    NetRequestManger.getInstance().LiShiLogin(account.getText().toString().trim(), password.getText().toString().trim(), "1", DeviceId);
//                }
//            });
        }

        doSomeThing();

    }

    private void doSomeThing() {

        btQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAllAcitivity();
            }
        });

        TimeCountDownUtil.CountDownTime(10);

        TimeCountDownUtil.setTimeOverListener(new TimeCountDownUtil.TimeOver() {
            @Override
            public void timeOverNow() {
                if (StringUtil.isNullOrEmpty(account.getText().toString().trim()) || StringUtil.isNullOrEmpty(password.getText().toString().trim())) {
                    ToastUtil.showToast("用户名或密码为空，请检查");
                    return;
                }
                iosLoadDialog.show();
                btLogin.setClickable(false);

                //对基础地址进行填写
                String baseUrl = (String) SPUtils.get(LoginActivity.this, Customer.LiSHI_INPUT_URL, "");
                if (StringUtil.isNullOrEmpty(baseUrl)) {
                    Base_URL = Customer.LiSHI_BASE_URL;
                } else {
                    Base_URL = baseUrl;
                }

                //
                checkAccountAndPassword(account.getText().toString().trim(), password.getText().toString().trim());
            }
        });



        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isNullOrEmpty(account.getText().toString().trim()) || StringUtil.isNullOrEmpty(password.getText().toString().trim())) {
                    ToastUtil.showToast("用户名或密码为空，请检查");
                    return;
                }
                iosLoadDialog.show();
                btLogin.setClickable(false);

                //对基础地址进行填写
                String baseUrl = (String) SPUtils.get(LoginActivity.this, Customer.LiSHI_INPUT_URL, "");
                if (StringUtil.isNullOrEmpty(baseUrl)) {
                    Base_URL = Customer.LiSHI_BASE_URL;
                } else {
                    Base_URL = baseUrl;
                }

                //
                checkAccountAndPassword(account.getText().toString().trim(), password.getText().toString().trim());
            }
        });

        setIp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //跳转页面 进行地址设置
                TimeCountDownUtil.CountDownTimeFinish();

                iosLoadDialog.show();
                startActivity(new Intent(LoginActivity.this, SettingIPActivity.class));
                iosLoadDialog.dismiss();
            }
        });

    }

    private void checkAccountAndPassword(String trim, String trim1) {
        jjhLoginBean = new JJHLoginBean(trim, trim1, "1", DeviceId);

        RetrofitClient.getInstance(LoginActivity.this, Base_URL).JJHLogin(jjhLoginBean, new BaseSubscriber<JJHLoginResult>(LoginActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                iosLoadDialog.dismiss();
                btLogin.setClickable(true);
                ToastUtil.showToast(e.message);
            }

            @Override
            public void onNext(JJHLoginResult jjhLoginResult) {

                TimeCountDownUtil.CountDownTimeFinish();

                btLogin.setClickable(true);
                //返回数据正常，进行正常解析
                if (jjhLoginResult.getCode().equals("200")) {
                    //返回数据是200 登录成功，进行页面跳转，以及正常数据保存
                    iosLoadDialog.dismiss();


                    startActivity(new Intent(LoginActivity.this, MainActivity.class));


                    SPUtils.put(LoginActivity.this, Customer.LISHI_ACCOUNT, account.getText().toString().trim());
                    SPUtils.put(LoginActivity.this, Customer.LISHI_PASSWORD, password.getText().toString().trim());
                    // 保存 token 后期接口 调用
                    SPUtils.put(LoginActivity.this, Customer.LISHI_ACCESSTOKEN, jjhLoginResult.getData().getUserInfo().getAccessToken());
                    SPUtils.put(LoginActivity.this, Customer.LISHI_REFRESHTOKEN, jjhLoginResult.getData().getUserInfo().getRefreshToken());

                    //保存businessOrgId  userName 游船订单需要用到
//                    SPUtils.put(LoginActivity.this,  Customer.JJH_BUSINESSORGID, jjhLoginResult.getData().getUserInfo().getBusinessOrgId() + "");
//                    SPUtils.put(LoginActivity.this, Customer.JJH_USERNAME, jjhLoginResult.getData().getUserInfo().getUserName());

                    SPUtils.put(LoginActivity.this, Customer.LISHI_IS_LOGIN, true);
                    headers.put("Token", jjhLoginResult.getData().getUserInfo().getAccessToken());

                    // 启动服务， 去更新 token
                    startService(new Intent(LoginActivity.this, RefreshTokenService.class));
                    finish();
                } else {
                    //对失败进行反馈
                    ToastUtil.showToast(jjhLoginResult.getMessage());
                    iosLoadDialog.dismiss();
                }
            }
        });
    }

    private void getDeviceId() {

        //获取设备唯一标识
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    DeviceId = GetDeviceId.getDeviceId(LoginActivity.this);
                    //获取保存在sd中的 设备唯一标识符
                    String readDeviceID = GetDeviceId.readDeviceID(LoginActivity.this);
                    //获取缓存在  sharepreference 里面的 设备唯一标识
                    String string = (String) SPUtils.get(LoginActivity.this, Customer.LISHI_DEVICE_ID, "");
                    //判断 app 内部是否已经缓存,  若已经缓存则使用app 缓存的 设备id
                    if (string != null && !string.equals("")) {
                        // 说明有保存，那么久将其放出去呗
                        if (readDeviceID.equals(string)) {
                            //缓存和文件地址一样，直接返回出去
                            DeviceId = readDeviceID;
                        }
                    } else {
                        DeviceId = GetDeviceId.getDeviceId(LoginActivity.this);
                        GetDeviceId.saveDeviceID(DeviceId, LoginActivity.this);
                    }
                    //最后再次更新app 的缓存
                    SPUtils.put(LoginActivity.this, Customer.LISHI_DEVICE_ID, DeviceId);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
